import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';
import type { Recordable } from '@vben/types';

import type { VbenFormSchema } from '#/adapter/form';
import type { DictApi, MachineryApi, WorkshopApi } from '#/api';

import { reactive, ref } from 'vue';

import { $t } from '@vben/locales';
import { getPopupContainer } from '@vben/utils';

import {
  DictResp,
  getAutoCode,
  getMachineryTypeHandleList,
  getSelectOptions,
  useFieldMap,
} from '#/api';

const switchValue = ref('');
const mes_machinery_status = reactive<DictApi.SelectOption[]>([]);
const workshopList = reactive<DictApi.SelectOption[]>([]);
const workshopMap = ref<Record<string, WorkshopApi.Datum>>();

/**
 * 获取下拉框数据，以及回填其他隐藏数据
 */
getSelectOptions('/mes/md/workshop/listAll', 'workshopName', 'workshopId').then(
  (res) => {
    // 将两个数组合并
    if (res) {
      // 检查 res.options 是否为数组，如果是则使用扩展运算符合并，否则将其作为空数组处理
      if (Array.isArray(res.options)) {
        workshopList.push(...res.options);
      }
      // 检查 res.oriData 是否为数组，如果不是则使用空数组
      const dataArray = Array.isArray(res.oriData) ? res.oriData : [];
      const workshopField = useFieldMap(dataArray, 'workshopId', [
        'workshopName',
        'workshopCode',
      ]);
      workshopMap.value = workshopField;
    }
  },
);

DictResp(['mes_machinery_status']).then((res) => {
  // 将两个数组合并
  if (res.mes_machinery_status) {
    mes_machinery_status.push(...res.mes_machinery_status);
  }
});
export function useSearchForm(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'machineryId',
      dependencies: {
        triggerFields: ['machineryId'],
        show: false,
      },
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入设备编码',
        class: 'mr-5',
      },
      fieldName: 'machineryCode',
      label: '设备编码',
      labelClass: 'text-[#606266] font-bold',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入设备名称',
      },
      fieldName: 'machineryName',
      label: '设备名称',
      labelClass: '  text-[#606266] font-bold',
    },
  ];
}

/**
 * 获取编辑表单的字段配置
 */
export function useSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'machineryId',
      dependencies: {
        triggerFields: ['machineryId'],
        show: false,
      },
    },

    {
      component: 'Input',
      fieldName: 'machineryCode',
      label: '设备编码',
      rules: 'required',
      formItemClass: 'col-span-1 col-start-1',
      componentProps: {
        placeholder: '请输入设备编号',
      },
      dependencies: {
        triggerFields: ['switch'],
        trigger(values) {
          values.machineryCode = switchValue;
        },
      },
    },
    {
      component: 'Switch',
      fieldName: 'switch',
      label: '自动生成',
      formItemClass: 'col-span-1',
      componentProps: {
        defaultValue: 0,
        onChange: (e: boolean) => {
          if (e) {
            getAutoCode('MACHINERY_CODE').then((res) => {
              switchValue.value = res.data;
            });
          } else {
            switchValue.value = '';
          }
        },
      },
      dependencies: {
        triggerFields: ['machineryId'],
        show(values) {
          return !values.machineryId && true;
        },
      },
    },
    {
      component: 'Input',
      fieldName: 'machineryName',
      label: '设备名称',
      rules: 'required',
      componentProps: {
        placeholder: '请输入设备名称',
      },
      formItemClass: 'col-span-2 col-start-1',
    },
    {
      component: 'Input',
      fieldName: 'machineryBrand',
      label: '品牌',
      componentProps: {
        placeholder: '请输入品牌',
      },
      formItemClass: 'col-span-2 col-start-1',
    },
    {
      component: 'ApiTreeSelect',
      componentProps: {
        api: getMachineryTypeHandleList,
        class: 'w-full',
        filterTreeNode(input: string, node: Recordable<any>) {
          if (!input || input.length === 0) {
            return true;
          }
          const title: string = node.machineryTypeName ?? '';
          if (!title) return false;
          return title.includes(input) || $t(title).includes(input);
        },
        getPopupContainer,
        labelField: 'machineryTypeName',
        showSearch: true,
        treeDefaultExpandAll: true,
        valueField: 'machineryTypeId',
        childrenField: 'children',
      },
      fieldName: 'machineryTypeId',
      label: '设备类型',
      formItemClass: 'col-span-2 col-start-1',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: workshopList,
        placeholder: '请选择所属车间',
        showSearch: true,
      },
      fieldName: 'workshopId',
      label: '所属车间',
      formItemClass: 'col-span-1 col-start-1',
    },
    {
      component: 'Input',
      fieldName: 'workshopName',
      label: '隐藏字段车间名字',
      dependencies: {
        triggerFields: ['workshopId'],
        trigger(values) {
          values.workshopName =
            workshopMap.value?.[values.workshopId]?.workshopName;
        },
        show: false,
      },
    },
    {
      component: 'Input',
      fieldName: 'workshopCode',
      label: '隐藏字段车间编码',
      dependencies: {
        triggerFields: ['workshopId'],
        trigger(values) {
          values.workshopCode =
            workshopMap.value?.[values.workshopId]?.workshopCode;
        },
        show: false,
      },
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: mes_machinery_status,
        placeholder: '请选择状态',
        showSearch: true,
      },
      fieldName: 'status',
      label: '设备状态',
      formItemClass: 'col-span-1 col-start-3',
    },

    {
      component: 'Textarea',
      componentProps: {
        placeholder: '请输入规格型号',
        maxLength: 50,
        rows: 3,
        showCount: true,
      },
      fieldName: 'machinerySpec',
      label: '规格型号',
      emptyStateValue: null,
      formItemClass: 'col-span-3 col-start-1 items-start',
    },

    {
      component: 'Textarea',
      componentProps: {
        placeholder: '请输入备注信息',
        maxLength: 50,
        rows: 3,
        showCount: true,
        class: 'w-full',
      },
      fieldName: 'remark',
      label: '备注',

      emptyStateValue: null,
      formItemClass: 'col-span-3 col-start-1 items-start',
    },
  ];
}

/**
 * 获取表格列配置
 * @param onView 查看详情回调
 */
export function useColumns(
  onView: (param: MachineryApi.Row) => void,
): VxeTableGridOptions<MachineryApi.Row>['columns'] {
  return [
    {
      field: 'checkbox',
      fixed: 'left',
      type: 'checkbox',
      width: 50,
    },
    {
      field: 'machineryCode',
      title: '设备编码',
      width: 150,
      cellRender: { name: 'CellButtonInfo', props: { onClick: onView } },
    },
    {
      field: 'machineryName',
      title: '设备名称',
    },
    {
      field: 'machineryBrand',
      title: '品牌',
    },
    {
      field: 'machinerySpec',
      title: '规格型号',
    },
    {
      field: 'workshopName',
      title: '所属车间',
    },
    {
      field: 'status',
      title: '设备状态',
      formatter: ({ cellValue }) => {
        const item = mes_machinery_status.find(
          (item) => item.value === cellValue,
        );
        return item?.label || '无';
      },
    },

    {
      title: '创建时间',
      field: 'createTime',
      width: 200,
    },
    {
      field: 'action',
      title: '操作',
      width: 150,
      fixed: 'right',
      align: 'center',
      slots: { default: 'action' },
    },
  ];
}
